import * as THREE from './three.min.js';
import * as TWEEN from './tween.js';
//import { Math } from './three.js';

var canvas;
var gl;

var ZW_Platform;
var ZW_PixelRatio;

var ZW_Scene;
var ZW_Camera;
var ZW_Renderer;
var ZW_BACK_COLOR = 0xffffff;
var ZW_BACK_ALPHA = 1.0;

var ZW_FinishSceneBox;
var ZW_SceneSize;
var ZW_PrimitiveViewDistance = 3.0;

var ZW_normalCamera;    //常规操作的相机

var ZW_CenterNode0;
var ZW_CenterNode;
var ZW_CameraNode;
var ZW_SceneParent;

var ZW_FpsRotH = -4.55;
var ZW_FpsRotV = 0;

var ZW_Width = 0;
var ZW_Height = 0;

var ZW_raycaster; //用于碰撞检测

var ZW_SpriteTagArray = [];  //精灵图tag数组
var ZW_SpriteNameArray = [];  //精灵图名字数组
var ZW_SpriteUvArray = [];  //精灵图uv数组

// var STATE = {
//   NONE: -1,
//   TOUCH_ROTATE: 0,
//   TOUCH_ZOOM_PAN: 1,
//   TOUCH_PAN: 2
// };

// var _state = STATE.NONE;
// var _movePrev = new THREE.Vector2();
// var _moveCurr = new THREE.Vector2();
// var _touchZoomDistanceStart = 1;
// var _touchZoomDistanceEnd = 1;
// var _panStart = new THREE.Vector2();
// var _panEnd = new THREE.Vector2();

var document = {};
document.createElementNS = function (ns, tagName) {
  if (tagName === 'canvas') {
    return null;
  } else if (tagName === 'img') {
    return canvas.createImage();
  }

  return null;
}

//加载回调
function OnModelProcess(value) {
  console.log(value);
}

//加载完成
function OnModelEnd() {

}

function genDebugInfos() {
  var str = " ZW_Platform = " + ZW_Platform;
  str += "\n ZW_PixelRatio = " + ZW_PixelRatio;
  str += "\n ZW_Width = " + ZW_Width;
  str += "\n ZW_Height = " + ZW_Height;

  var info = my.getSystemInfoSync();
  str += "\n windowWidth = " + info.windowWidth;
  str += "\n windowHeight = " + info.windowHeight;
  return str;
}

//引擎初始化
function InitEngine(canvasId) {

  ZW_Platform = my.getSystemInfoSync().platform;
  ZW_PixelRatio = my.getSystemInfoSync().pixelRatio;
  my._createCanvas({
    id: canvasId,
    success: (c) => {
      var webgl = c.getContext('webgl');

      canvas = c;
      gl = webgl;

      canvas.width *= ZW_PixelRatio;
      canvas.height *= ZW_PixelRatio;
      ZW_Width = canvas.width;
      ZW_Height = canvas.height;
      // var info = my.getSystemInfoSync();
      // ZW_Height = info.windowHeight;
      // ZW_Width = info.windowWidth;

      InitScene();
    }
  });
}

//3d场景初始化
function InitScene() {
  ZW_Scene = new THREE.Scene()
  //ZW_Camera = new THREE.PerspectiveCamera(20, canvas.width / canvas.height, 1, 100000);
  ZW_Renderer = new THREE.WebGLRenderer({ antialias: true, canvas: canvas, context: gl, alpha: true })

  ZW_normalCamera = new THREE.PerspectiveCamera(80, canvas.width / canvas.height, 0.0001, 100000); //常规视角相机

  //ZW_normalCamera = new THREE.OrthographicCamera(ZW_Width / - 2, ZW_Width / 2, ZW_Height / 2, ZW_Height / -2, 0.1, 10000);

  ZW_raycaster = new THREE.Raycaster();

  ZW_normalCamera.position.set(0, 0, 0);

  //console.log([canvas.width,canvas.height]);

  var geometry = new THREE.Geometry();
  var material = new THREE.MeshBasicMaterial({
    color: 0xff0000
  });

  ZW_SceneParent = new THREE.Mesh(geometry, material);
  ZW_Scene.add(ZW_SceneParent);

  ZW_CenterNode0 = new THREE.Mesh(geometry);
  ZW_SceneParent.add(ZW_CenterNode0);


  ZW_CenterNode = new THREE.Mesh(geometry);
  ZW_CenterNode0.add(ZW_CenterNode);


  ZW_CameraNode = new THREE.Mesh(geometry);
  ZW_CenterNode.add(ZW_CameraNode);

  //   var geometry = new THREE.SphereGeometry(5, 100, 100 );
  // var material = new THREE.MeshBasicMaterial( {color: 0xffff00} );
  // var sphere = new THREE.Mesh( geometry, material );
  // sphere.position.set(0,0,0)
  // ZW_SceneParent.add( sphere );

  var geometry = new THREE.PlaneGeometry(100, 100);
  var material = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide });
  var plane = new THREE.Mesh(geometry, material);
  //plane.position.set(0,600,0);
  //ZW_SceneParent.add( plane );

  // my.alert({
  //     content: ZW_Scene,
  //   });

  // var urls = ['http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pano/px.jpg', 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pano/nx.jpg',
  //   'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pano/nz.jpg', 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pano/pz.jpg',
  //   'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pano/py.jpg', 'http://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/pano/ny.jpg'];
  //var loader = new THREE.CubeTextureLoader().load(canvas, urls);
  //  ZW_Scene.background = loader;

  ZW_normalCamera.up.x = 0;
  ZW_normalCamera.up.y = 0;
  ZW_normalCamera.up.z = 1;
  ZW_normalCamera.lookAt(lookAtPos);

  SetSceneRot(0, 0);
  SetBackColor(100, 100, 100, 0.0);
  animate();
}

var lookAtPos = new THREE.Vector3(-1000, 0, 0);

function SetFov(value) {
  if (!value) return;
  ZW_normalCamera.fov = value;
  ZW_normalCamera.updateProjectionMatrix();
  ShowProcess();
}

function AddSkyBox(urls, tag) {
  //ZW_Platform = 'Android';
  var size = 1000;
  var myFragmentShader;
  if (ZW_Platform == 'Android') {
    myFragmentShader = 'uniform sampler2D texture0;  \
        uniform sampler2D texture1;  \
        uniform sampler2D texture2;  \
        uniform sampler2D texture3;  \
        uniform sampler2D texture4;  \
        uniform sampler2D texture5;  \
        uniform int bid; \
        uniform float alpha; \
        varying vec3 vUv;   \
        void main(void){    \
            if(bid == 0){ \
                if(vUv.z < 1.01 && vUv.z > 0.99)    \
                    gl_FragColor = texture2D(texture0, vec2(1.0-vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 2.01 && vUv.z > 1.99)    \
                    gl_FragColor = texture2D(texture1, vec2(1.0-vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 3.01 && vUv.z > 2.99)    \
                    gl_FragColor = texture2D(texture2, vec2(1.0-vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 4.01 && vUv.z > 3.99)    \
                    gl_FragColor = texture2D(texture3, vec2(1.0-vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 5.01 && vUv.z > 4.99)    \
                    gl_FragColor = texture2D(texture4, vec2(1.0-vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else \
                    gl_FragColor = texture2D(texture5, vec2(1.0-vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
            }else { \
                gl_FragColor = vec4(1.0, 0.0, vUv.z / 255.0, 1.0);  \
            }   \
        }';
  } else {
    myFragmentShader = 'uniform sampler2D texture0;  \
        uniform sampler2D texture1;  \
        uniform sampler2D texture2;  \
        uniform sampler2D texture3;  \
        uniform sampler2D texture4;  \
        uniform sampler2D texture5;  \
        uniform int bid; \
        uniform float alpha; \
        varying vec3 vUv;   \
        void main(void){    \
            if(bid == 0){ \
                if(vUv.z < 1.01 && vUv.z > 0.99)    \
                    gl_FragColor = texture2D(texture0, vec2(1.0-vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 2.01 && vUv.z > 1.99)    \
                    gl_FragColor = texture2D(texture1, vec2(1.0-vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 3.01 && vUv.z > 2.99)    \
                    gl_FragColor = texture2D(texture2, vec2(1.0-vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 4.01 && vUv.z > 3.99)    \
                    gl_FragColor = texture2D(texture3, vec2(1.0-vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else if(vUv.z < 5.01 && vUv.z > 4.99)    \
                    gl_FragColor = texture2D(texture4, vec2(1.0-vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
                else \
                    gl_FragColor = texture2D(texture5, vec2(1.0-vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);    \
            }else { \
                gl_FragColor = vec4(1.0, 0.0, vUv.z / 255.0, 1.0);  \
            }   \
        }';
  }

  var myVertexShader = 'varying vec3 vUv; \
        attribute vec3 uvs; \
        void main(){    \
            vUv = uvs;   \
            vec4 mvPosition = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
            gl_Position = mvPosition;   \
        }';

  var e0 = new Float32Array(6 * 3 * 6);
  e0 = [-size, -size, size, -size, -size, -size, size, -size, size, //前
  -size, -size, -size, size, -size, -size, size, -size, size,
  -size, size, size, -size, size, -size, size, size, size, //后
  -size, size, -size, size, size, -size, size, size, size,
  -size, size, size, -size, size, -size, -size, -size, size, //左
  -size, size, -size, -size, -size, -size, -size, -size, size,
    size, size, size, size, size, -size, size, -size, size, //右
    size, size, -size, size, -size, -size, size, -size, size,
  -size, size, size, -size, -size, size, size, size, size, //上
  -size, -size, size, size, -size, size, size, size, size,
  -size, size, -size, -size, -size, -size, size, size, -size, //下
  -size, -size, -size, size, -size, -size, size, size, -size];

  var c = new Float32Array(6 * 3 * 6);
  for (var i = 0; i < c.length; i++) {
    c[i] = 255 * 1.0;
  }

  var f = new Float32Array(6 * 3 * 6);
  f = [0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0,  //前
    0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0,
    1.0, 1.0, 2.0, 1.0, 0.0, 2.0, 0.0, 1.0, 2.0,  //后
    1.0, 0.0, 2.0, 0.0, 0.0, 2.0, 0.0, 1.0, 2.0,
    0.0, 1.0, 3.0, 0.0, 0.0, 3.0, 1.0, 1.0, 3.0,  //左
    0.0, 0.0, 3.0, 1.0, 0.0, 3.0, 1.0, 1.0, 3.0,
    1.0, 1.0, 4.0, 1.0, 0.0, 4.0, 0.0, 1.0, 4.0,  //右
    1.0, 0.0, 4.0, 0.0, 0.0, 4.0, 0.0, 1.0, 4.0,
    0.0, 1.0, 5.0, 0.0, 0.0, 5.0, 1.0, 1.0, 5.0,  //上
    0.0, 0.0, 5.0, 1.0, 0.0, 5.0, 1.0, 1.0, 5.0,
    0.0, 0.0, 6.0, 0.0, 1.0, 6.0, 1.0, 0.0, 6.0,  //下
    0.0, 1.0, 6.0, 1.0, 1.0, 6.0, 1.0, 0.0, 6.0];

  var uniforms0 = {
    bid: {
      value: 0
    },
    alpha: {
      value: 1.0
    },
    texture0: {
      value: null
    },
    texture1: {
      value: null
    },
    texture2: {
      value: null
    },
    texture3: {
      value: null
    },
    texture4: {
      value: null
    },
    texture5: {
      value: null
    }
  };

  var textureid0 = gl.createTexture();
  var textureid1 = gl.createTexture();
  var textureid2 = gl.createTexture();
  var textureid3 = gl.createTexture();
  var textureid4 = gl.createTexture();
  var textureid5 = gl.createTexture();

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex0 = new THREE.TextureLoader().load(canvas, urls[0]);
    imgTex0.minFilter = THREE.NearestFilter;
    uniforms0.texture0.value = imgTex0;

    console.log(imgTex0);

    var imgTex1 = new THREE.TextureLoader().load(canvas, urls[1]);
    imgTex1.minFilter = THREE.NearestFilter;
    uniforms0.texture1.value = imgTex1;

    var imgTex2 = new THREE.TextureLoader().load(canvas, urls[2]);
    imgTex2.minFilter = THREE.NearestFilter;
    uniforms0.texture2.value = imgTex2;

    var imgTex3 = new THREE.TextureLoader().load(canvas, urls[3]);
    imgTex3.minFilter = THREE.NearestFilter;
    uniforms0.texture3.value = imgTex3;

    var imgTex4 = new THREE.TextureLoader().load(canvas, urls[4]);
    imgTex4.minFilter = THREE.NearestFilter;
    uniforms0.texture4.value = imgTex4;

    var imgTex5 = new THREE.TextureLoader().load(canvas, urls[5]);
    imgTex5.minFilter = THREE.NearestFilter;
    uniforms0.texture5.value = imgTex5;
  } else {  //iOS平台纹理处理

    var image0 = canvas.createImage();
    image0.src = urls[0];

    image0.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid0);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image0);
      uniforms0.texture0.value = textureid0;
      ShowProcess();
    }


    var image1 = canvas.createImage();
    image1.src = urls[1];
    var textureid1 = gl.createTexture();
    image1.onload = function () {
      gl.activeTexture(gl.TEXTURE3);
      gl.bindTexture(gl.TEXTURE_2D, textureid1);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image1);
      myuniform.texture1.value = textureid1;
      ShowProcess();
    }

    var image2 = canvas.createImage();
    image2.src = urls[2];
    var textureid2 = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE2);
      gl.bindTexture(gl.TEXTURE_2D, textureid2);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      myuniform.texture2.value = textureid2;
      ShowProcess();
    }

    var image3 = canvas.createImage();
    image3.src = urls[3];
    var textureid3 = gl.createTexture();
    image3.onload = function () {
      gl.activeTexture(gl.TEXTURE4);
      gl.bindTexture(gl.TEXTURE_2D, textureid3);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image3);
      myuniform.texture3.value = textureid3;
      ShowProcess();
    }

    var image4 = canvas.createImage();
    image4.src = urls[4];
    var textureid4 = gl.createTexture();
    image4.onload = function () {
      gl.activeTexture(gl.TEXTURE5);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image4);
      myuniform.texture4.value = textureid4;
      ShowProcess();
    }
    var image5 = canvas.createImage();
    image5.src = urls[5];
    var textureid5 = gl.createTexture();
    image5.onload = function () {
      gl.activeTexture(gl.TEXTURE1);
      gl.bindTexture(gl.TEXTURE_2D, textureid5);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image5);
      myuniform.texture5.value = textureid5;
      ShowProcess();
    }
  }

  var planeMaterial0 = new THREE.ShaderMaterial({
    uniforms: uniforms0,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide,
    wireframe: false
  });

  var mygeo0 = new THREE.BufferGeometry();
  mygeo0.addAttribute('position', new THREE.Float32BufferAttribute(e0, 3));  //顶点位置
  //mygeo0.addAttribute('fcolor', new THREE.Float32BufferAttribute(c, 3));     //设置的顶点颜色
  mygeo0.addAttribute('uvs', new THREE.Float32BufferAttribute(f, 3));    //顶点uv

  var mesh0 = new THREE.Mesh(mygeo0, planeMaterial0);
  mesh0.name = tag;
  //mesh0.renderOrder = renderOrder;
  mesh0.material.depthWrite = false;
  mesh0.material.transparent = true;
  mesh0.material.side = THREE.DoubleSide;
  //mesh0.frustumCulled = false;
  mesh0.position.set(0, 0, 0);
  mesh0.scale.set(1, 1, 1);

  if (ZW_Platform == 'Android') {
  } else {
    mesh0.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid0);
      gl.activeTexture(gl.TEXTURE3);
      gl.bindTexture(gl.TEXTURE_2D, textureid1);
      gl.activeTexture(gl.TEXTURE2);
      gl.bindTexture(gl.TEXTURE_2D, textureid2);
      gl.activeTexture(gl.TEXTURE4);
      gl.bindTexture(gl.TEXTURE_2D, textureid3);
      gl.activeTexture(gl.TEXTURE5);
      gl.bindTexture(gl.TEXTURE_2D, textureid4);
      gl.activeTexture(gl.TEXTURE1);
      gl.bindTexture(gl.TEXTURE_2D, textureid5);

    }
  }

  ZW_SceneParent.add(mesh0);

  //my.alert({ content: 'viewcube' });
}

function AddSkyDome0(url, tag) {
  //skydome
  var geometry = new THREE.SphereBufferGeometry(500, 20, 20);

  geometry.scale(-100, 100, 100);

  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });


  var mesh1 = new THREE.Mesh(geometry, planeMaterial);
  mesh1.name = tag;
  //mesh1.renderOrder = 0;
  //mesh1.material.depthTest = true;
  mesh1.material.depthWrite = true;
  //mesh1.material.transparent = true;

  // mesh1.position.x = posX - ZW_Width / 2 + width / 2;
  // mesh1.position.y = -posY + ZW_Height / 2 - height / 2;

  // mesh1.width = width;
  // mesh1.height = height;

  //mesh1.rotation.z = Math.PI/4;

  mesh1.rotation.x = Math.PI / 2;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
    }

    var image2 = canvas.createImage();
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid;
      ShowProcess();
    }
  }

  ZW_SceneParent.add(mesh1);
  ShowProcess();
}

//添加穹顶
function AddSkyDome(url, tag) {
  //skydome
  var geometry = new THREE.SphereBufferGeometry(500, 20, 20);

  //var geometry = new ZW.SphereBufferGeometry(500, 60, 40);
  //console.log(geometry.attributes.uv.array);


  // invert the geometry on the x-axis so that all of the faces point inward
  geometry.scale(-1000, 1000, 1000);

  var imgTex1 = new THREE.TextureLoader().load(canvas, url)
  // imgTex1.minFilter = THREE.NearestFilter;
  var material = new THREE.MeshBasicMaterial({
    map: imgTex1,
    wireframe: false
  });

  var mymodel = ZW_SceneParent.getObjectByName(tag);
  if (mymodel)
    ZW_SceneParent.remove(mymodel);

  var mesh = new THREE.Mesh(geometry, material);
  mesh.name = tag;
  mesh.rotation.x = Math.PI / 2;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    material.map = imgTex;
  } else {  //iOS平台纹理处理


    var image2 = canvas.createImage();
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid = gl.createTexture();
    image2.onload = function () {

      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      mesh.material.uniforms.map.value = textureid;
      //material.map.needsUpdate = true;
      ShowProcess();
    }

    var uvArray = mesh.geometry.attributes.uv.array;
    for (var i = 0; i < uvArray.length / 2; i++) {
      uvArray[i * 2 + 1] = 1.0 - uvArray[i * 2 + 1];
    }
    mesh.geometry.attributes.uv.needsUpdate = true;

    mesh.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
    }
  }

  ZW_SceneParent.add(mesh);
}

//背景色设置
function SetBackColor(red, green, blue, alpha) {
  var hex = "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);

  ZW_BACK_COLOR = hex;

  if (typeof (alpha) == "undefined") {
    ZW_BACK_ALPHA = 1.0;
  } else {
    ZW_BACK_ALPHA = alpha;
  }

  ZW_Renderer.setClearColor(ZW_BACK_COLOR, ZW_BACK_ALPHA)
}

//场景渲染
function ShowProcess() {
  ZW_Renderer.setViewport(0, 0, canvas.width, canvas.height);
  ZW_Renderer.clear();
  ZW_Renderer.render(ZW_Scene, ZW_normalCamera);
}

function animate() {
  canvas.requestAnimationFrame(animate);
  TWEEN.update(); //动画更新
  ShowProcess();
}

function testfunc() {
  my.alert({
    content: 'ZW_Scene',
  });
}

//添加精灵图
function AddSprite(tag, posX, posY, posZ, width, height, jsonData, url, aniData, zIndex) {
  var picWidth = jsonData.meta.size.w;
  var picHeight = jsonData.meta.size.h;

  ZW_SpriteTagArray.push(tag);
  ZW_SpriteNameArray.push([]);
  ZW_SpriteUvArray.push([]);
  var FramesData = jsonData['frames'];
  //ZW_SpriteUvArray = [];
  for (var i = 0; i < aniData.length; i++) {
    //my.alert({content: FramesData[aniData[i]]});
    var uv = [];
    uv.push(FramesData[aniData[i]].frame.x / picWidth);
    uv.push(FramesData[aniData[i]].frame.y / picHeight);

    if (FramesData[aniData[i]].rotated) {
      uv.push((FramesData[aniData[i]].frame.x + FramesData[aniData[i]].frame.h) / picWidth);
      uv.push((FramesData[aniData[i]].frame.y + FramesData[aniData[i]].frame.w) / picHeight);
    } else {
      uv.push((FramesData[aniData[i]].frame.x + FramesData[aniData[i]].frame.w) / picWidth);
      uv.push((FramesData[aniData[i]].frame.y + FramesData[aniData[i]].frame.h) / picHeight);
    }


    ZW_SpriteNameArray[ZW_SpriteNameArray.length - 1].push(aniData[i]);
    ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1].push(uv);
  }


  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][0];
  f[1] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][1];
  f[2] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][0];
  f[3] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][3];
  f[4] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][2];
  f[5] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][1];

  f[6] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][0];
  f[7] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][3];
  f[8] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][2];
  f[9] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][3];
  f[10] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][2];
  f[11] = ZW_SpriteUvArray[ZW_SpriteUvArray.length - 1][0][1];

  // f[0] = 0.0;
  // f[1] = 0.0;
  // f[2] = 0.0;
  // f[3] = 1.0;
  // f[4] = 1.0;
  // f[5] = 0.0;

  // f[6] = 0.0;
  // f[7] = 1.0;
  // f[8] = 1.0;
  // f[9] = 1.0;
  // f[10] = 1.0;
  // f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = false;
  mesh1.material.depthWrite = false;
  mesh1.material.transparent = true;

  mesh1.position.set(posX, posY, posZ);
  // mesh1.position.x = posX - ZW_Width / 2 + width / 2;
  // mesh1.position.y = -posY + ZW_Height / 2 - height / 2;

  mesh1.rotation.y = Math.PI / 2;

  mesh1.width = width;
  mesh1.height = height;

  mesh1.rotation.z = Math.PI / 2;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
    }

    var image2 = canvas.createImage();
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid = gl.createTexture();
    image2.onload = function () {

      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid;
      ShowProcess();
    }
  }

  ZW_SceneParent.add(mesh1);
  ShowProcess();

  if (aniData.length > 1) {
    StartSpriteAnimation(tag, aniData, aniData.length * 1000 / 15.0);
  }

  // my.alert({content: tag});


  // let fs = my.getFileSystemManager();
  // fs.readFile({
  //   filePath: url,
  //   encoding: "utf8",
  //   success: result => {
  //     console.log(result);
  //   }
  // });
  // return;
  // my.downloadFile({
  //   url: url,
  //   success({ apFilePath }) {
  //     my.alert({
  //       content: apFilePath,
  //     });
  //     let fs = my.getFileSystemManager();
  //     fs.readFile({
  //       filePath: apFilePath,
  //       encoding: "utf8",
  //       success: result => {
  //         var metaData = result.data.meta;
  //         var frames = result.data.frames;
  //         console.log(metaData);
  //         console.log(frames);
  //         // for(var i=0; i<frames.length;i++)
  //         // {
  //         //   console.log(frames[i].frame);
  //         // }
  //         // my.alert({
  //         //   content: result,
  //         // });
  //       }
  //     })
  //   }
  // });
}

//位移动画
function StartPositionAnimation(tag, startPos, endPos, time, delay, repeat) {
  if (!delay) delay = 0;
  if (!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = { x: startPos.x, y: startPos.y };
  // console.log(startPos.x,startPos.y);
  // console.log(endPos.x,endPos.y);
  new TWEEN.Tween(coords)
    .to({ x: endPos.x, y: endPos.y }, time)
    .repeat(repeat)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(function () {
      //console.log(coords.y);
      mymodel.position.x = coords.x - ZW_Width / 2 + mymodel.width / 2;
      mymodel.position.y = -coords.y + ZW_Height / 2 - mymodel.height / 2;

      //ShowProcess();
    })
    .delay(delay)
    .start();
}

//位移动画
function StartPosition3DAnimation(tag, startPos, endPos, time, delay, repeat, pingpong) {
  if (!delay) delay = 0;
  if (!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = { x: startPos.x, y: startPos.y, z: startPos.z };
  // console.log(startPos.x,startPos.y);
  // console.log(endPos.x,endPos.y);

  var update = function () {
    mymodel.position.x = coords.x;
    mymodel.position.y = coords.y;
    mymodel.position.z = coords.z;
    ShowProcess();
  };

  var posAni = new TWEEN.Tween(coords)
    .to({ x: endPos.x, y: endPos.y, z: endPos.z }, time)
    .repeat(repeat)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(update)
    .delay(delay);

  var rePosAni = new TWEEN.Tween(coords)
    .to({ x: startPos.x, y: startPos.y, z: startPos.z }, time)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(update);

  if (pingpong) {
    posAni.chain(rePosAni);
    rePosAni.chain(posAni);
  }
  posAni.start();
}

//alpha动画
function StartAlphaAnimation(tag, startValue, endValue, time, delay, repeat) {
  if (!delay) delay = 0;
  if (!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = { x: startValue };
  new TWEEN.Tween(coords)
    .to({ x: endValue }, time)
    .repeat(repeat)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(function () {
      mymodel.material.uniforms.alpha.value = coords.x;
      //ShowProcess();
    })
    .delay(delay)
    .start();
}

//旋转动画
function StartRotationAnimation(tag, startValue, endValue, time, delay, repeat) {
  if (!delay) delay = 0;
  if (!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = { x: startValue };
  new TWEEN.Tween(coords)
    .to({ x: endValue }, time)
    .repeat(repeat)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(function () {
      mymodel.rotation.z = coords.x;

      //ShowProcess();
    })
    .delay(delay)
    .start();
}

//大小动画
function StartScaleAnimation(tag, startValue, endValue, time, delay, repeat) {
  if (!delay) delay = 0;
  if (!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = { x: startValue };
  new TWEEN.Tween(coords)
    .to({ x: endValue }, time)
    .repeat(repeat)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(function () {
      mymodel.scale.x = mymodel.scale.x * coords.x;
      mymodel.scale.y = mymodel.scale.y * coords.x;

      //ShowProcess();
    })
    .delay(delay)
    .start();
}

//大小动画
function StartScaleXYAnimation(tag, startXValue, endXValue, startYValue, endYValue, time, delay, repeat) {
  if (!delay) delay = 0;
  if (!repeat) repeat = 0;
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var coords = { x: startXValue, y: startYValue };
  new TWEEN.Tween(coords)
    .to({ x: endXValue, y: endYValue }, time)
    .repeat(repeat)
    .easing(TWEEN.Easing.Quadratic.Out)
    .onUpdate(function () {
      mymodel.scale.x = coords.x;
      mymodel.scale.y = coords.y;

      //ShowProcess();
    })
    .delay(delay)
    .start();
}

//播放帧动画
function StartSpriteAnimation(tag, aniData, time) {
  var myIndex = -1;
  for (var i = 0; i < ZW_SpriteTagArray.length; i++) {
    if (tag == ZW_SpriteTagArray[i]) {
      myIndex = i;
      break;
    }
  }
  if (myIndex < 0) return -1;  //没找到相关的tag，直接退出
  var mymodel = ZW_SceneParent.getObjectByName(tag);
  var uvAttribute = mymodel.geometry.attributes.uv;
  var uvArray = mymodel.geometry.attributes.uv.array;

  var frame = { x: 0 };
  new TWEEN.Tween(frame)
    .to({ x: aniData.length - 1 }, time)
    .repeat(Infinity)
    .easing(TWEEN.Easing.Linear.None)
    .onUpdate(function () {

      uvArray[0] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][0];
      uvArray[1] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][1];
      uvArray[2] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][0];
      uvArray[3] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][3];
      uvArray[4] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][2];
      uvArray[5] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][1];

      uvArray[6] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][0];
      uvArray[7] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][3];
      uvArray[8] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][2];
      uvArray[9] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][3];
      uvArray[10] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][2];
      uvArray[11] = ZW_SpriteUvArray[myIndex][parseInt(frame.x)][1];

      uvAttribute.needsUpdate = true;
      //ShowProcess();
    })
    .start();
}

//添加普通的图片
function AddImage(tag, posX, posY, width, height, url, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = true;
  mesh1.material.depthWrite = true;
  mesh1.material.transparent = true;

  mesh1.position.x = posX - ZW_Width / 2 + width / 2;
  mesh1.position.y = -posY + ZW_Height / 2 - height / 2;

  mesh1.width = width;
  mesh1.height = height;

  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
    }

    var image2 = canvas.createImage();
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid;
      ShowProcess();
    }
  }

  ZW_SceneParent.add(mesh1);
  ShowProcess();
  //my.alert({content: 'url'});

  // var coords = { x: 0, y: 0 };
  // new TWEEN.Tween(coords) 
  //       .to({ x: 100, y: 200 }, 600)
  //       .repeat(50)
  //       .easing(TWEEN.Easing.Quadratic.Out) 
  //       .onUpdate(function() { 
  //           mesh1.position.x = coords.x;
  //           mesh1.position.y = -coords.y;
  //           mesh1.material.uniforms.alpha.value = coords.x/100.0
  //           ShowProcess();
  //       })
  //       .start(); 
}

//添加普通的图片
function AddImage3D(tag, posX, posY, posZ, rotateX, rotateY, rotateZ, width, height, url, zIndex) {
  var uniforms = {
    texture1: {
      value: null
    },
    alpha: {
      value: 1.0
    },
  };

  var myFragmentShader = '  \
  uniform float alpha; \
    uniform sampler2D texture1;  \
        varying vec2 vUv;   \
        void main(void){    ';
  if (ZW_Platform == 'Android') { //android平台纹理处理    
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,1.0-vUv.y))*vec4(1.0,1.0,1.0,alpha);}';
  } else {
    myFragmentShader += 'gl_FragColor = texture2D(texture1, vec2(vUv.x,vUv.y));}';
  }
  var myVertexShader = 'varying vec2 vUv; \
        void main(){    \
            vUv = uv;   \
            gl_Position = projectionMatrix*modelViewMatrix * vec4( position, 1.0 ); \
        }';

  var planeMaterial = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: myVertexShader,
    fragmentShader: myFragmentShader,
    side: THREE.DoubleSide
  });

  var e = new Float32Array(6 * 3);
  e[0] = -width / 2;
  e[1] = height / 2;
  e[2] = 0.0;
  e[3] = -width / 2;
  e[4] = -height / 2;
  e[5] = 0.0;
  e[6] = width / 2;
  e[7] = height / 2;
  e[8] = 0.0;

  e[9] = -width / 2;
  e[10] = -height / 2;
  e[11] = 0.0;
  e[12] = width / 2;
  e[13] = -height / 2;
  e[14] = 0.0;
  e[15] = width / 2;
  e[16] = height / 2;
  e[17] = 0.0;

  var f = new Float32Array(6 * 2);
  f[0] = 0.0;
  f[1] = 0.0;
  f[2] = 0.0;
  f[3] = 1.0;
  f[4] = 1.0;
  f[5] = 0.0;

  f[6] = 0.0;
  f[7] = 1.0;
  f[8] = 1.0;
  f[9] = 1.0;
  f[10] = 1.0;
  f[11] = 0.0;

  var mygeo = new THREE.BufferGeometry();
  mygeo.addAttribute('position', new THREE.Float32BufferAttribute(e, 3));
  mygeo.addAttribute('uv', new THREE.Float32BufferAttribute(f, 2));

  var mesh1 = new THREE.Mesh(mygeo, planeMaterial);
  mesh1.name = tag;
  mesh1.renderOrder = zIndex;
  mesh1.material.depthTest = true;
  mesh1.material.depthWrite = true;
  mesh1.material.transparent = true;

  mesh1.position.x = posX;
  mesh1.position.y = posY;
  mesh1.position.z = posZ;

  mesh1.rotation.x = rotateX;
  mesh1.rotation.y = rotateY;
  mesh1.rotation.z = rotateZ;

  mesh1.width = width;
  mesh1.height = height;

  //mesh1.rotation.z = Math.PI/4;

  if (ZW_Platform == 'Android') { //android平台纹理处理
    var imgTex = new THREE.TextureLoader().load(canvas, url);
    imgTex.minFilter = THREE.NearestFilter;

    uniforms.texture1.value = imgTex;
  } else {  //iOS平台纹理处理
    mesh1.onBeforeRender = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
    }

    // var image2 = canvas.createImage();
    var image2 = document.createElementNS("", "img");
    //image2.src = "https://morefun-active.oss-cn-beijing.aliyuncs.com/tmp/model/back-img.png";
    image2.src = url;
    var textureid = gl.createTexture();
    image2.onload = function () {
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, textureid);
      // Set the parameters so we can render any size image.
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Upload the image into the texture.
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image2);
      uniforms.texture1.value = textureid;
      ShowProcess();
    }
  }

  ZW_SceneParent.add(mesh1);
  ShowProcess();
  //my.alert({content: 'url'});

  // var coords = { x: 0, y: 0 };
  // new TWEEN.Tween(coords) 
  //       .to({ x: 100, y: 200 }, 600)
  //       .repeat(50)
  //       .easing(TWEEN.Easing.Quadratic.Out) 
  //       .onUpdate(function() { 
  //           mesh1.position.x = coords.x;
  //           mesh1.position.y = -coords.y;
  //           mesh1.material.uniforms.alpha.value = coords.x/100.0
  //           ShowProcess();
  //       })
  //       .start(); 
}

function GetClickedTag(event) {
  //my.alert({content: event});
  var mouse = new THREE.Vector2();
  mouse.x = ((event.touches[0].x * ZW_PixelRatio) / ZW_Width) * 2 - 1;
  mouse.y = -((event.touches[0].y * ZW_PixelRatio) / ZW_Height) * 2 + 1;

  // mouse.x = ((event.touches[0].x ) / ZW_Width) * 2 - 1;
  // mouse.y = -((event.touches[0].y) / ZW_Height) * 2 + 1;

  ZW_raycaster.setFromCamera(mouse, ZW_normalCamera);

  var interArray = [];
  interArray.push(ZW_SceneParent);
  // var mymodel = ZW_SceneParent.getObjectByName('tag');

  // if (mymodel) interArray.push(mymodel);

  var intersects = ZW_raycaster.intersectObjects(interArray, true);
  //console.log(intersects[0]);

  if (intersects[0]) {
    return intersects[0].object.name;

    //my.alert({content: intersects[0].object.name});
    //my.alert({content: intersects[0]});
  }
  return null;
}

function SetSceneRot(xOffset, yOffset) {
  // var xOffset = _moveCurr.x - _movePrev.x;
  // 				var yOffset = _moveCurr.y - _movePrev.y;

  ZW_FpsRotH -= xOffset;
  ZW_FpsRotV += yOffset;

  // console.log(ZW_FpsRotH + " + " + ZW_FpsRotV)
  //my.alert({content: ZW_normalCamera});
  if (Math.abs(ZW_FpsRotV) > Math.PI * 0.5) {
    ZW_FpsRotV -= yOffset;
  }
  //my.alert({content: ZW_normalCamera});

  ZW_normalCamera.up.x = 0;
  ZW_normalCamera.up.y = 0;
  ZW_normalCamera.up.z = 1;

  var axisX = ZW_normalCamera.position.x - Math.cos(ZW_FpsRotV) * Math.sin(ZW_FpsRotH);
  var axisY = ZW_normalCamera.position.y + Math.cos(ZW_FpsRotV) * Math.cos(ZW_FpsRotH);
  var axisZ = ZW_normalCamera.position.z + Math.sin(ZW_FpsRotV);

  ZW_normalCamera.updateProjectionMatrix();
  ZW_normalCamera.lookAt(new THREE.Vector3(axisX, axisY, axisZ));

  lookAtPos = new THREE.Vector3(axisX, axisY, axisZ);
  ShowProcess();

  //my.alert({content: ZW_normalCamera});

  // ZW_Scene.rotation.y -= xOffset;
  //  ZW_Scene.rotation.x += yOffset;
  //ShowProcess();
  //my.alert({content: ZW_normalCamera});

}

function SwitchSkyBox(tag1, tag2, time) {
  var mymodel1 = ZW_SceneParent.getObjectByName(tag1);
  var mymodel2 = ZW_SceneParent.getObjectByName(tag2);

  var lookX = lookAtPos.x * 100;
  var lookY = lookAtPos.y * 100;
  if (mymodel1) {
    mymodel1.visible = true;
    // StartAlphaAnimation(tag1, 1.0, 1.0, 0);
    // StartPosition3DAnimation(tag1, dot, new THREE.Vector3(0 - lookX, 0 - lookY, lookAtPos.z), time);

  }
  if (mymodel2) {
    mymodel2.visible = false;
    // StartAlphaAnimation(tag2, 1.0, 0.0, time);
    // StartPosition3DAnimation(tag2, new THREE.Vector3(lookX, lookY, lookAtPos.z), dot, time);

  }


  // mymodel1.renderOrder = 2;
  // mymodel2.renderOrder = 1;

  ShowProcess();
  var dot = new THREE.Vector3(0, 0, 0);

  // StartAlphaAnimation(tag1, 1.0, 1.0, 0);
  // StartAlphaAnimation(tag2, 1.0, 0.0, time);

  // StartPosition3DAnimation(tag2, new THREE.Vector3(lookX, lookY, lookAtPos.z), dot, time);
  // StartPosition3DAnimation(tag1, dot, new THREE.Vector3(0 - lookX, 0 - lookY, lookAtPos.z), time);
}

function removeItemsByName(inName) {
  for (var i = 0; i < ZW_SceneParent.children.length; i++) {
    var child = ZW_SceneParent.children[i];
    if (child == null)
      continue;

    if (child.name.indexOf(inName) != -1) {
      ZW_SceneParent.remove(child);
      i--;
    }
  }
  ShowProcess();
}

function setNodeVisible(tag, isV) {
  var mymodel1 = ZW_SceneParent.getObjectByName(tag);
  mymodel1.visible = isV;
}

function isHaveObject(tag) {
  var mymodel1 = ZW_SceneParent.getObjectByName(tag);
  if (mymodel1)
    return true;
  else return false;
}

module.exports = {
  InitEngine: InitEngine,
  SetBackColor: SetBackColor,
  AddImage: AddImage,
  AddImage3D: AddImage3D,
  GetClickedTag: GetClickedTag,
  AddSprite: AddSprite,
  StartSpriteAnimation: StartSpriteAnimation,
  StartPositionAnimation: StartPositionAnimation,
  StartPosition3DAnimation: StartPosition3DAnimation,
  StartAlphaAnimation: StartAlphaAnimation,
  StartRotationAnimation: StartRotationAnimation,
  StartScaleAnimation: StartScaleAnimation,
  StartScaleXYAnimation: StartScaleXYAnimation,
  SetSceneRot: SetSceneRot,
  AddSkyBox: AddSkyBox,
  SwitchSkyBox: SwitchSkyBox,
  AddSkyDome0: AddSkyDome0,
  AddSkyDome: AddSkyDome,
  SetFov: SetFov,
  removeItemsByName: removeItemsByName,
  genDebugInfos: genDebugInfos,
  setNodeVisible: setNodeVisible,
  isHaveObject: isHaveObject
}
